<?php
/**
 * 条目推荐到推荐位 自定义公共组件
 * User: apple
 * Date: 1/23/22
 * Time: 9:54 PM
 */

use \app\assets\BackendAsset as Asset;
use \app\models\tableModel\AdminRoleModel;

/* @var $this yii\web\View */
/* @var $_params_ array 总参数变量 */
/* @var $type int 类型, 参考{PositionModel -> $typeList}的键 */

// HTML
$template = <<<EOL

<el-dialog title="推荐到推荐位" :visible.sync="showDialog" class="dialog-medium scroll-dialog body-nop"
        :lock-scroll="true" width="80%" :close-on-click-modal="false"
        modal-append-to-body>

    <el-scrollbar class="main-scroller">
        <el-container class="index-wrapper">
            <el-main class="content-wrapper transits bg-white pt-20"
                element-loading-text="加载中..." v-loading.lock="isLoading"
                style="min-height: 500px">
                <!-- 主列表 表格 START -->
                <el-checkbox-group v-model="handleSelectList">
                    <el-checkbox v-for="(item, key) in dataList" :label="item.id" :key="key"
                                 border size="medium" :style="getItemStyle(key)">
                        {{item.name}}
                    </el-checkbox>
                </el-checkbox-group>
                <div v-show="!isLoading">
                    <el-empty v-if="!dataList || dataList.length < 1" description="暂无推荐位"></el-empty>
                    <div v-if="!dataList || dataList.length < 1" class="border-1px-bottom"></div>
                </div>
                <!-- 主列表 表格 END -->
                <!-- 分页 START -->
                <div class="block pagination">
                    <el-pagination @size-change="handleSizeChange"
                                   @current-change="handleCurrentChange"
                                   :current-page="page"
                                   :page-sizes="[20, 50, 100, 200]"
                                   :page-size="20"
                                   layout="total, sizes, prev, pager, next, jumper"
                                   :total="dataTotal">
                    </el-pagination>
                </div>
                <!-- 分页 END -->
            </el-main>
        </el-container>
    </el-scrollbar>
    
    <div slot="footer">
        <el-button type="danger" size="mini" @click="showDialog = false">取消</el-button>
EOL;
if (AdminRoleModel::checkAuth('push', 'positionData', 'backend')) {
    $template .= <<<EOL
    
        <el-button size="mini" type="primary" @click="submit">
            提交
        </el-button>

EOL;
}
$template .= <<<EOL

    </div>
</el-dialog>

EOL;

$js = <<<EOL
Vue.component('item-to-position', {
    template: `$template`,
    props: {},
    data: function () {
        return {
            dataList: [], // 数据列表
            fromIdList: [], // 推送编号列表
            handleSelectList: [], // 已选择推荐位编号列表
            page: 1, // 推荐位数据分页当前页
            pageSize: 20, // 推荐位数据分页大小
            dataTotal: 0, // 推荐位数据分页总数
            showDialog: false, // 是否展示弹出层
            isLoading: true, // 是否加载中
        };
    },
    created: function () {
            
        var that = this;
        this.\$nextTick(function () {});
    },
    methods: {
        /**
         * 获取下列表
         */
        getList: function () {

            // 加载中
            this.isLoading = true;
            
            // 正在加载...
            var loadingInstance = ELEMENT.Loading.service({
                fullscreen: false,
                text: '加载中...'
            });
            var that = this;

            // 获取各模块的值
            $.ajax({
                url: \$w.getApiUrl('position.list'),
                type: 'get',
                data: {
                    page: this.page,
                    page_size: this.pageSize,
                    data_from_ids: this.fromIdList,
                    search: {
                        type: $type
                    }
                },
                dataType: "json",
                success: function (event) {

                    that.\$nextTick(function () {

                        // 加载中
                        that.isLoading = false;
                        // 隐藏正在加载
                        loadingInstance.close();
                    });

                    // 必须先登录
                    if (parseInt(event.no) === 401) {

                        that.\$message({
                            type: 'warning',
                            showClose: true,
                            message: '登录超时，请重新登录'
                        });

                        // 几秒之后移除
                        return setTimeout(function () {
                            window.parent.location.href = \$w.getPageUrl('login');
                        }, 810);
                    }

                    // 操作失败显示错误信息
                    if (parseInt(event.no) !== 200) {

                        return that.\$message({
                            type: 'error',
                            showClose: true,
                            message: event.msg
                        });
                    }

                    // 数据
                    that.dataList = event.data.list;
                    for (var i in that.dataList) {
                        if (!that.dataList.hasOwnProperty(i)) continue;
                        that.\$set(that.dataList[i], 'newSort', 0);
                        that.\$set(that.dataList[i], 'sortEdit', false);
                        // 条目数据已推荐 选择
                        if (that.dataList[i]['had_item'] &&
                            !\$w.in_array(that.dataList[i]['id'], that.handleSelectList))
                        {
                            that.handleSelectList.push(that.dataList[i]['id']);
                        }
                    }
                    // 总条目
                    that.dataTotal = parseInt(event.data.total);
                },
                error: function () {

                    // 加载中
                    this.isLoading = false;
                    // 按钮正在加载
                    loadingInstance.close();
                    return that.\$message({
                        type: 'error',
                        showClose: true,
                        message: '操作频繁，请稍后尝试'
                    });
                }
            });
        },
        /**
         * 分页大小监测处理
         * @param \$val
         */
        handleSizeChange: function (\$val) {
            // 分页大小赋值
            this.pageSize = \$val;
            // 默认到 第一页
            this.page = 1;
            this.getList();
        },
        /**
         * 分页跳转监测处理
         * @param \$val
         */
        handleCurrentChange: function (\$val) {
            \$val = !parseInt(\$val) ? 1 : \$val;
            this.page = \$val;
            this.getList();
        },
        /**
         * 提交
         */
        submit: function () {

            // 新闻列表为空
            if (!this.fromIdList || this.fromIdList.length <= 0) {
                return this.\$message({
                    showClose: true,
                    type: 'error',
                    message: '请选择推送条目'
                });
            }

            // 推荐位列表
            var posIdList = this.handleSelectList;
            // 推荐位列表为空
            if (!posIdList || posIdList.length <= 0) {
                return this.\$message({
                    showClose: true,
                    type: 'error',
                    message: '请选择推荐位'
                });
            }
            
            var that = this;

            this.\$confirm('此操作将[推送]数据到推荐位中, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(function () {

                // 正在加载。。
                var loadingInstance = ELEMENT.Loading.service({
                    fullscreen: false,
                    text: '加载中...'
                });

                // 获取各模块的值
                $.ajax({
                    url: \$w.getApiUrl('positionData.push'),
                    type: 'POST',
                    data: {
                        fromIdList: that.fromIdList,
                        fromType: $type,
                        posIdList: posIdList
                    },
                    dataType: "json",
                    success: function (event) {

                        that.\$nextTick(function () {
                            // 隐藏正在加载
                            loadingInstance.close();
                        });

                        // 必须先登录
                        if (parseInt(event.no) === 403) {

                            that.\$message({
                                type: 'warning',
                                showClose: true,
                                message: '登录超时，请重新登录'
                            });

                            // 几秒之后移除
                            return setTimeout(function () {
                                window.parent.location.href = \$w.getPageUrl('login');
                            }, 810);
                        }

                        // 失败的返回|提示
                        if (parseInt(event.no) !== 200) {

                            return that.\$message({
                                showClose: true,
                                type: 'error',
                                message: event.msg
                            });
                        }

                        // 放空列表
                        that.getList();

                        // 成功 加载下列表
                        return that.\$nextTick(function () {
                            // 提示成功
                            that.\$message({
                                showClose: true,
                                type: 'success',
                                message: '推送成功'
                            });
                            
                            that.showDialog = false;
                        });
                    },
                    error: function () {

                        that.\$nextTick(function () {
                            // 隐藏正在加载
                            loadingInstance.close();
                        });

                        return that.\$message({
                            showClose: true,
                            type: 'error',
                            message: '请求用频繁稍后尝试'
                        });
                    }
                });
            });
        },
        /**
         * 获取条目的样式
         * @param \$key
         * @param \$itemWidth
         * @returns {*}
         */
        getItemStyle: function (\$key, \$itemWidth) {
            // 条目宽度
            \$itemWidth = \$itemWidth || 240;
            // 文档总宽度(两边共40px宽度)
            var documentWidth = $('body').width() - 40;
            var itemNum = parseInt(documentWidth / \$itemWidth);
            var itemMargin = parseInt(
                (documentWidth - (itemNum * \$itemWidth)) / itemNum / 2);
            if (itemMargin <= 5) return this.getItemStyle(\$key, \$itemWidth - 2);
            return {
                width: \$itemWidth + 'px',
                marginLeft: itemMargin + 'px',
                marginRight: itemMargin + 'px'
            };
        },
    },
    watch: {
        /**
         * 检测是否展示推荐位
         */
        showDialog: function (\$val) {
            // 不展示略过
            if (!\$val) return true;
            
            // 清空列表
            this.dataList = [];
            // 默认到 第一页
            this.page = 1;
            // 清空 当前选择列表
            this.handleSelectList = [];
            this.getList();
        }
    }
});
EOL;

if (empty($this->params['reg_item_to_position'])) Asset::addScript($this, '/plugin/ace-editor/1.4.9/ace.min.js');
if (empty($this->params['reg_item_to_position'])) Asset::addScript($this, '/plugin/ace-editor/1.4.9/ext-language_tools.min.js');
if (empty($this->params['reg_item_to_position'])) Asset::addScript($this, '/js/beautify-html.js');
if (empty($this->params['reg_item_to_position'])) $this->registerJs($js);
// 已注册过
$this->params['reg_item_to_position'] = true;

echo "<item-to-position ref=\"itemToPosition\"></item-to-position>";
?>
